<template>
  <div class="login-container">
    <div class="login-box">
      <!-- 头像区域 -->
      <h1>后台登录</h1>
      <!-- 表单区域 -->
      <el-form :model='loginForm' :rules="formRules" ref="formRef">
        <el-form-item prop="username">
          <el-input prefix-icon="el-icon-user" v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input prefix-icon="el-icon-key" v-model='loginForm.password' type="password"></el-input>
        </el-form-item>
        <el-form-item class="sort">
          <el-button type="primary" @click="confirm">登录</el-button>
          <el-button type="info" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      redirect: undefined,
      formRules: {
        username: [
          { required: true, message: '请输入登录名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
    confirm () {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/' })
            })
            .catch(err => err)
        }
      })
    },
    resetForm () {
      this.$refs.formRef.resetFields()
    }
  }
}
</script>
<style lang="less" scoped>
.login-container {
  font-family: sans-serif;
  background: #34495e;
  height: 100%;
}
.login-box {
  width: 400px;
  padding: 40px 50px 30px;
  position: absolute;
  top: 48%;
  left: 50%;
  transform: translate(-50%,-50%);
  background: #2b2a2a;
  text-align: center;
  border-radius: 20px;
  opacity: 0.9;
  h1 {
    color: white;
    text-transform: uppercase;
    font-weight: 500;
  }
}
</style>
